package com.my.house.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * spring 配置工具
 * @author yangll
 */
@Slf4j
@Component
public class SpringUtil implements ApplicationContextAware {


    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
        log.info("spring容器初始化完成");
    }

    /**
     * 获取注册的spring bean
     * @param tClass beanClass
     * @return Bean
     * @param <T> bean类型
     */
    public static <T> T getBean(Class<T> tClass) {
        if (Objects.isNull(context)) {
            return null;
        }
        return context.getBean(tClass);
    }

    /**
     * 根据bean名称获取注册的spring bean
     * @param beanName bean名称
     * @param tClass beanClass
     * @return Bean
     * @param <T> bean类型
     */
    public static <T> T getBean(String beanName, Class<T> tClass) {
        if (Objects.isNull(context)) {
            return null;
        }
        return context.getBean(beanName, tClass);
    }

    /**
     * 根据key名称获取配置值
     * @param key 名称
     * @return 配置值
     */
    public static String getProperty(String key) {
        if (Objects.isNull(context)) {
            return null;
        }
        return context.getEnvironment().getProperty(key);
    }
}
